package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 27设置参数限值,模拟量
 * Created by zwz on 2020/4/22.
 */
public class Cmd_27_0AFragment extends BaseFragment {

    @BindView(R.id.sp_id)
    Spinner spId;
    @BindView(R.id.cb_enalbe)
    CheckBox cbEnalbe;
    @BindView(R.id.edt_min)
    EditText edtMin;
    @BindView(R.id.edt_max)
    EditText edtMax;
    @BindView(R.id.edt_ll)
    EditText edtLl;
    @BindView(R.id.edt_l)
    EditText edtL;
    @BindView(R.id.edt_h)
    EditText edtH;
    @BindView(R.id.edt_hh)
    EditText edtHh;


    public static Cmd_27_0AFragment newInstance() {
        Bundle args = new Bundle();
        Cmd_27_0AFragment fragment = new Cmd_27_0AFragment();
        fragment.setArguments(args);


        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_27_0a;
    }

    @Override
    protected void initView() {
        String[] ids = {"1", "2", "3", "4"};
        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, ids);
        spId.setAdapter(mAdapter);

        edtMin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                edtLl.setText(edtMin.getText().toString());
                edtL.setText(edtMin.getText().toString());
            }
        });
        edtMax.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                edtH.setText(edtMax.getText().toString());
                edtHh.setText(edtMax.getText().toString());
            }
        });
    }

    /**
     * 转换成800-4000,AD
     * @param data ad
     * @return
     */
    private   String parseAD(String data){
    float d = Float.parseFloat(data);
    String min= edtMin.getText().toString();
    String max = edtMax.getText().toString();
    float d_min = Float.parseFloat(min);
    float d_max = Float.parseFloat(max);

    d = d /(d_max-d_min)*3200f+800f;//（信号强度值*3200）/255+800
        return String.format(Locale.CHINA,"%.0f",d);

}

    private void set() {
       String min= edtMin.getText().toString();
        String max = edtMax.getText().toString();
        String ll = edtLl.getText().toString();
        String l = edtL.getText().toString();
        String h= edtH.getText().toString();
        String hh= edtHh.getText().toString();
        String id = String.format(Locale.CHINA, "%02x", Integer.parseInt(spId.getSelectedItem().toString()));
        if(min.isEmpty()||max.isEmpty()||ll.isEmpty()||l.isEmpty()||h.isEmpty()||hh.isEmpty()){
            toastShow("以上参数不能为空");
            return;
        }

        String enable=cbEnalbe.isChecked()?"01":"00";

//         min= "-20";
//         max = "600";
//         ll = "1316";
//         l ="1832";
//         h= "2864";
//         hh= "3380";

         ll = String.format(Locale.CHINA, "%04x", Long.parseLong(parseAD(ll)));
        l = String.format(Locale.CHINA, "%04x", Long.parseLong(parseAD(l)));
        h = String.format(Locale.CHINA, "%04x", Long.parseLong(parseAD(h)));
        hh = String.format(Locale.CHINA, "%04x", Long.parseLong(parseAD(hh)));
      min=  BleUtils.getFloat(Float.parseFloat(min));
        max=  BleUtils.getFloat(Float.parseFloat(max));

        Log.e("xxxxxxx","ll:"+ll);
        Log.e("xxxxxxx","l:"+l);
        Log.e("xxxxxxx","h:"+h);
        Log.e("xxxxxxx","hh:"+hh);
        Log.e("xxxxxxx","min:"+min);
        Log.e("xxxxxxx","max:"+max);
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(CmdConfig.CMD_27_0A).append(" ")// 模拟量
                .append(id).append(" ")// 通道
                .append(max).append(" ")// 量程上限
                .append(min).append(" ")//量程下限
                .append(ll.substring(2,4)).append(" ")//
                .append(ll.substring(0,2)).append(" ")//
                .append(l.substring(2,4)).append(" ")//
                .append(l.substring(0,2)).append(" ")//
                .append(h.substring(2,4)).append(" ")//
                .append(h.substring(0,2)).append(" ")//
                .append(hh.substring(2,4)).append(" ")//
                .append(hh.substring(0,2)).append(" ")//
                .append(enable);
//        模拟量参数限值数据包： 量程上限（4byte） +量程下限（4byte） +报警下下
//        限（2byte） +报警下限（2byte） +报警上限（2byte） +报警上上限（2byte）
//        +采集使能标志（1byte）。

        sendData(stringBuilder.toString());

    }

    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_27, data);

        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();

                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_27)&&
                        data[13].equals(CmdConfig.CMD_27_0A)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }

    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }

}
